package com.taotao.sso.controller;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.utils.CookieUtils;
import com.taotao.sso.pojo.User;
import com.taotao.sso.pojo.UserResult;
import com.taotao.sso.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "register" ,method = RequestMethod.GET)
	public String toRegister(){
		return "register";
	}
	@RequestMapping(value = "login" ,method = RequestMethod.GET)
	public String toLogin(){
		return "login";
	}
	
	@RequestMapping(value="check/{param}/{type}",method = RequestMethod.GET)
	public ResponseEntity<Boolean> checkUser(@PathVariable("param")String param,@PathVariable("type")Integer type){
		try {
			if (StringUtils.isBlank(param) || type == null || type.intValue() < 1 || type.intValue() > 3) {
				return ResponseEntity.badRequest().build();
			}
			Boolean b = this.userService.checkUser(param, type);
			if (b == null) {
				ResponseEntity.badRequest().build();
			}
			return ResponseEntity.ok(!b);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity<UserResult> register(@Valid User user,BindingResult result){
		
		try {
		//验证参数
		if (result.hasErrors()) {
			//手记错误信息
			ArrayList<String> msgs = new ArrayList<>();
			for (ObjectError error : result.getAllErrors()) {
				msgs.add(error.getDefaultMessage());
			}
			//参数有错,响应400
			return ResponseEntity.badRequest().body(UserResult.build(400, StringUtils.join(msgs,"|")));
		}
			Boolean b = this.userService.register(user);
			if (b) {
				return ResponseEntity.ok(UserResult.ok());
			} 
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(UserResult.build(500, e.getMessage()));
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(UserResult.build(500, "O(∩_∩)O哈哈~"));
		
	}
	
	@RequestMapping(value="doLogin",method = RequestMethod.POST)
	@ResponseBody
	public UserResult login(@RequestParam("username") String username,@RequestParam("password") String password
			,HttpServletRequest req,HttpServletResponse rep){
		try {
			  //验证用户,生成token
		String token = this.userService.login(username,password);
		if (StringUtils.isNotEmpty(token)) {
			//如果不为空,则把token写入cookie中
			CookieUtils.setCookie(req, rep, "TT_TOKEN", token,10800);
			//响应200成功
			return UserResult.ok();
		}
		//否则可能是用户信息输入有误	
		return UserResult.build(400, "用户名或密码错误");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return UserResult.build(500, "服务器内部错误");
	}

	@RequestMapping(value = "query/{token}",method = RequestMethod.GET)
	public ResponseEntity<User> query(@PathVariable("token") String token){
		try {
			User user = userService.query(token);
			if (user == null) {
				return ResponseEntity.notFound().build();
			}
			return ResponseEntity.ok(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
}
